package tcp

object TcpClientManager {

    private var mTcp: TcpClientThread? = null

    private var mAddress: String = ""
    private var mPort: Int = 8089
    private var mListener: OnNetThreadListener? = null

    fun close() {
        mTcp?.close()
    }

    fun connect(address: String, port: Int, listener: OnNetThreadListener): TcpClientThread {
        if (mTcp != null) {
            try {
                mTcp?.close()
                mTcp = null
            } catch (e: Exception) {}
        }
        mAddress = address
        mPort = port
        mListener = listener
        // 打开TCP
        val tcp = TcpClientThread(mAddress, mPort, listener)
        tcp.start()
        mTcp = tcp
        return tcp
    }

    fun reconnect() {
        close()
        mListener?: return
        connect(mAddress, mPort, mListener!!)
    }

    fun send(data: ByteArray) {
        mTcp?.send(data)
    }
}